#include "serverwidget.h"
#include "ui_serverwidget.h"
#include <QDebug>

ServerWidget::ServerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerWidget)
{
    ui->setupUi(this);
    setWindowTitle("服务器: 8888");
    tcpServer = NULL;
    tcpSocket = NULL;
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any, 8888);
    connect(tcpServer, &QTcpServer::newConnection,
            [=]() {
                // 取出建立好连接的套接字
                tcpSocket = tcpServer->nextPendingConnection();
                // 获取对方的ip和端口
                QString ip = tcpSocket->peerAddress().toString();
                qint16 port = tcpSocket->peerPort();
                QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);

                // 连接信息显示在内容只读区
                ui->textEditRead->setText(temp);

                // 接收数据
                connect(tcpSocket, &QTcpSocket::readyRead,
                        [=]() {
                           // ui->textEditRead->append("客户端: ");
                            QByteArray array = tcpSocket->readAll();
                            ui->textEditRead->append(QString("客户端: ").append(array));
                        }
                        );

            }

            );

   // tcpSocket = new tcpSocket(this);
}

ServerWidget::~ServerWidget()
{
    delete ui;
}

// close按钮槽函数
void ServerWidget::on_buttonClose_clicked()
{
    if (tcpSocket == NULL) {
        return;
    }
    // 主动和客户端断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    tcpSocket = NULL;
    // 关闭窗口
    this->close();
}


// 发送按钮槽函数
void ServerWidget::on_buttonSend_clicked()
{
    if (tcpSocket == NULL) {
        return;
    }
    // 获取编辑区的内容
    QString str = ui->textEditWrite->toPlainText();
    tcpSocket->write(str.toUtf8().data());

    // 清空编辑区
    ui->textEditWrite->clear();
}
